package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
	"sync"
)

var wg sync.WaitGroup

func main() {
	conn, err := net.Dial("tcp", "0.0.0.0:50000")
	if err != nil {
		fmt.Println("dial err:", err)
		return
	}
	process(conn)
}

func process(conn net.Conn) {
	defer conn.Close()
	fmt.Println("Hello Connor")
	wg.Add(1)
	go accept(conn)
	go sendStr(conn)
	wg.Wait()
	fmt.Println("closed...")
}

func accept(conn net.Conn) {
	for {
		reader := bufio.NewReader(conn)
		str, err := reader.ReadString('\n')
		if err != nil {
			wg.Done()
			return
		}
		str = strings.TrimSpace(str)
		fmt.Println("Xuyi Said:", str)
		if str == "bye" {
			fmt.Println("Xuyi has Bye Bye...")
			wg.Done()
			return
		}
	}
}

func sendStr(conn net.Conn) {
	for {
		str := inputStr()
		str = strings.TrimSpace(str)
		fmt.Println("Me Said:", str)
		str += "\n"
		_, err := conn.Write([]byte(str))
		if err != nil {
			fmt.Println("会话已结束。。。")
			return
		}
		if str == "bye" {
			fmt.Println("Me exit...")
			wg.Done()
			return
		}
	}
}

func inputStr() (str string) {
	reader := bufio.NewReader(os.Stdin)
	str, _ = reader.ReadString('\n')
	return
}
